package com.example.rubbish.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.rubbish.DataBase.Record;
import com.example.rubbish.R;

import java.util.List;

public class RecordAdapter extends ArrayAdapter<Record> {


    private  int resourceId;
    private List<Record> mRecords;
    public RecordAdapter(@NonNull Context context, int textViewResourceId, @NonNull List<Record> objects) {
        super(context,  textViewResourceId, objects);
        resourceId=textViewResourceId;
        mRecords=objects;

    }

    public void setData(List<Record> data){
        mRecords=data;
        this.notifyDataSetChanged();
    }
    public void set(int position , Record record){
        mRecords.set(position,record);
        this.notifyDataSetChanged();
    }

    @Nullable
    @Override
    public Record getItem(int position) {
        return mRecords.get(position);
    }


    public void removeItem(@Nullable Record object) {
        int position = getPosition(object);
        if(position>-1){
            mRecords.remove(position);

        }
        this.notifyDataSetChanged();

    }



    public void addItem(@Nullable Record object) {
        mRecords.add(object);
        this.notifyDataSetChanged();

    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        Record record = getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView==null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder =new ViewHolder();
            viewHolder.recordGarbage =view.findViewById(R.id.text_garbage);
            viewHolder.recordCate=view.findViewById(R.id.text_cate);
            viewHolder.recordDate= view.findViewById(R.id.text_time);
            view.setTag(viewHolder);
        }
        else {
            view=convertView;
            viewHolder=(ViewHolder) view.getTag();
        }
        viewHolder.recordGarbage.setText(record.getGarbageName());
        viewHolder.recordCate.setText(record.getCateName());
        viewHolder.recordDate.setText(record.getTime());

        return view;
    }

    class ViewHolder {
        TextView recordGarbage;
        TextView recordCate;
        TextView recordDate;
    }
}
